<?php

namespace console\controllers;



use yii\console\Controller;

class BackupController extends Controller
{
    /**
     *  php yii backup/backup-databases
     * 数据库备份
     */
    public function actionBackupDatabases(){
        // mysqldump -u root -p --databases choose test > roverliang.sql
        $root_path = \Yii::$app->basePath.'/../';
        $file_path = $root_path.'/backup/';
        $pwd = \Yii::$app->components['db']['password'];
        $dsn = \Yii::$app->components['db']['dsn'];
        $dababases = substr($dsn,(strpos($dsn,'dbname='))+7);
        $file_name = $dababases.'_'.date('Ymd').'.sql';
        $cmd = "mysqldump -u root -p$pwd --databases $dababases > $file_path$file_name";
        if(!is_dir($file_path))
        {
            mkdir($file_path);
        }
        if(function_exists("shell_exec")){
            shell_exec($cmd);
            //删除一个月之前的备份
            $a_month_ago = date("Ymd", strtotime("-1 month"));
            $a_month_ago_file = $file_path.$dababases.'_'.$a_month_ago.'.sql';
            if(file_exists($a_month_ago_file)){
                unlink($a_month_ago_file);
            }
            echo '备份成功！'. "\n";
        }else{
            echo '需要开启shell_exec权限' . "\n";
        }
        exit;
    }

}